package com.cxz.study.domain.common;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;

/**
 * @className: CommonModel
 * @author: ocxz1
 * @date: 2025/6/13 下午6:59
 * @Version: 1.0
 * @description: ddd-struct3
 */
public class CommonModel<T extends CommonModel<?>> {
    @SuppressWarnings("unchecked")
    public static <T> T generate() {
        try {
            // 获取调用此方法的类
            Class<?> callerClass = getCallerClass();

            // 获取带有一个String参数的构造器
            Constructor<?> constructor = callerClass.getDeclaredConstructor(String.class);

            // 生成UUID
            String uuid = UUID.randomUUID().toString();

            // 调用构造器创建实例
            return (T) constructor.newInstance(uuid);
        } catch (NoSuchMethodException | InstantiationException |
                 IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("Failed to generate instance", e);
        }
    }

    // 获取调用generate方法的类
    private static Class<?> getCallerClass() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        // 跳过前两个元素(当前方法和getStackTrace)
        for (int i = 2; i < stackTrace.length; i++) {
            try {
                Class<?> clazz = Class.forName(stackTrace[i].getClassName());
                if (CommonModel.class.isAssignableFrom(clazz) && clazz != CommonModel.class) {
                    return clazz;
                }
            } catch (ClassNotFoundException e) {
                // 忽略
            }
        }
        throw new RuntimeException("Could not determine caller class");
    }
}
